﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

/// <summary>
/// 工具类:所有WEP中使用的工具函数都在其中
/// </summary>
public class Tools
{
    /// <summary>
    /// 声明用于发送邮件的连接信息
    /// </summary>
    private static string SMTPHost = "smtp.exmail.qq.com";
    private static string SMTPAccount = "Verified@fanquan1314.com";
    private static string SMTPPassword = "138fq5985fq";
    private static string SMTPFrom = "Verified@fanquan1314.com";
    private static int SMTPPort = 25;

    /// <summary>
    /// 用于发送启用密码保护时用的邮件邮件，可能抛出异常
    /// </summary>
    /// <param name="to">用户填写的安全邮箱地址</param>
    /// <param name="userID">用户ID，用于逻辑操作</param>
    /// <param name="username">用户名，用于在邮件内显示</param>
    /// <returns></returns>
    /// <exception cref="Exception"></exception>
    public static void SendVerifyEmail(string to, string userID, string username)
    {
        //建立smtpClient对象
        SmtpClient smtpClient = new SmtpClient(SMTPHost,SMTPPort);
        //smtpClient.EnableSsl = true;
        //通过网络发送
        smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
        //创建验证信息
        smtpClient.Credentials = new NetworkCredential(SMTPAccount, SMTPPassword);

        //创建邮件主体
        MailMessage mailMessage = new MailMessage(SMTPFrom, to);
        //邮件标题
        mailMessage.Subject = "We Easy Project密码保护验证邮件";
        //邮件编码
        mailMessage.BodyEncoding = Encoding.UTF8;

        //创建邮件正文中的链接
        string url = "http://localhost:46745/emailVerified.aspx?userID=" + userID + "&_t=" + BitConverter.ToString(SHA1.Create().ComputeHash(Encoding.Unicode.GetBytes(username))).Replace("-", "");
        //创建邮件正文
        mailMessage.Body = "尊敬的 " + username + " 您好！<br>感谢您使用 We Easy Project 密码保护功能<br>请点击以下链接来完成邮箱验证<br><a href=\"" + url + "\">" + url + "</a>";

        //将邮件正文标记为HTML语言
        mailMessage.IsBodyHtml = true;
        mailMessage.Priority = MailPriority.High;
        //发送邮件
        try
        {
            smtpClient.Send(mailMessage);
        }
        catch (Exception)
        {
            throw;
        }
    }

    /// <summary>
    /// 发送在找回密码时验证用的邮件，可能抛出异常
    /// </summary>
    /// <param name="to">用户填写的安全邮箱地址</param>
    /// <param name="userID">用户ID，用于逻辑操作</param>
    /// <param name="username">用户名，用于在邮件内显示</param>
    /// <returns></returns>
    /// <exception cref="Exception"></exception>
    public static void SendFindPasswordEmail(string to, string userID, string username)
    {
        SmtpClient smtpClient = new SmtpClient(SMTPHost, SMTPPort);
        //smtpClient.EnableSsl = true;
        smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
        smtpClient.Credentials = new NetworkCredential(SMTPAccount, SMTPPassword);

        MailMessage mailMessage = new MailMessage(SMTPFrom, to);
        mailMessage.Subject = "We Easy Project密码保护验证邮件";
        mailMessage.BodyEncoding = Encoding.UTF8;

        string url = "http://localhost:46745/resetPassword.aspx?userID=" + userID + "&_t=" + BitConverter.ToString(SHA1.Create().ComputeHash(Encoding.Unicode.GetBytes(username))).Replace("-", "");
        mailMessage.Body = "尊敬的 " + username + " 您好！<br>您正在 We Easy Project 找回您的密码<br>请点击以下链接来完成密码重置<br><a href=\"" + url + "\">" + url + "</a>";

        mailMessage.IsBodyHtml = true;
        mailMessage.Priority = MailPriority.High;
        try
        {
            smtpClient.Send(mailMessage);
        }
        catch (Exception)
        {
            throw;
        }
    }

    /// <summary>
    /// 比较两个byte[]是否相等
    /// </summary>
    /// <param name="a"></param>
    /// <param name="b"></param>
    /// <returns></returns>
    public static bool byteArrayEquals(byte[] a, byte[] b)
    {
        if (a.Length != b.Length)
        {
            return false;
        }
        for (int i = 0; i < a.Length; i++)
        {
            if (a[i] != b[i])
            {
                return false;
            }
        }
        return true;
    }

    /// <summary>
    /// 文件上传函数
    /// 转储上传的文件
    /// 为适应版本管理上传，添加默认参数
    /// </summary>
    /// <param name="path"></param>
    /// <param name="fileupload"></param>
    /// <param name="IsEditionManagement"></param>
    /// <param name="username"></param>
    public static void upload(Page page, string path, FileUpload fileupload, bool IsEditionManagement = false, string username = "")
    {
        bool fileok = false;
        string filename;
        if (fileupload.HasFile)
        {
            string fileException = Path.GetExtension(fileupload.FileName).ToLower();
            //检测文件格式
            //string[] allowedException = { ".jpg", ".bmp", ".gif" };
            //for (int i = 0; i < allowedException.Length; i++)
            //{
            //    if (fileException == allowedException[i])
            //        fileok = true;
            //}
            fileok = true;
        }
        if (fileok)
        {
            if (Directory.Exists(path))
            {

            }
            else
            {
                Directory.CreateDirectory(path);
            }

            if (IsEditionManagement)
            {
                filename = fileupload.FileName + "_" + username;
            }
            else
            {
                filename = fileupload.FileName;
            }

            if (File.Exists(path + "/" + filename))
            {
                page.ClientScript.RegisterStartupScript(page.GetType(), "ss", "<script>alert('已有同名文件存在!')</script>");
                return;
            }
            else
            {
                fileupload.SaveAs(path + "/" + filename);
            }
        }
    }

    /// <summary>
    /// 删除空目录
    /// </summary>
    /// <param name="path"></param>
    /// <returns>true: 删除成功; false: 文件夹不空，未删除</returns>
    public static bool DeleteEmptyDirectory(string path)
    {
        DirectoryInfo info = new DirectoryInfo(path);
        if (info.GetFiles().Length + info.GetDirectories().Length == 0)
        {
            info.Delete(true);
            return true;
        }
        else
        {
            return false;
        }
    }
}